<template>
  <Dialog
    :show="dialogConfig.show"
    :title="dialogConfig.title"
    :buttons="dialogConfig.buttons"
    width="400px"
    :showCancel="false"
    @close="dialogConfig.show = false"
  >
    <el-form
      :model="formData"
      :rules="rules"
      ref="formDataRef"
      label-width="80px"
      @submit.prevent
    >
      <!--input输入-->
      <el-form-item
        label="标题"
        prop="title"
      >
        <el-input
          clearable
          placeholder="标题"
          v-model.trim="formData.title"
        ></el-input>
      </el-form-item>
      <!-- prop用于校验 -->
      <el-form-item
        label="板块"
        prop="boardIds"
      >
        <el-cascader
          clearable
          placeholder="请选择板块"
          v-model="formData.boardIds"
          :options="boardList"
          :props="boardProps"
          style="width: 100%;"
        ></el-cascader>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
const { proxy } = getCurrentInstance();

const formData = ref({});
const formDataRef = ref();
const rules = {
  boardIds: [{ required: true, message: "请选择板块信息" }],
};

const api = {
  loadBoard: 'board/loadBoard',
  updateBoard: '/forum/updateBoard'
}

// 板块信息
const boardProps = {
  multiple: false,
  checkStrictly: true,
  value: 'boardId',
  label: 'boardName'
}
const boardList = ref([])
const loadBoardList = async () => {
  let result = await proxy.Request({
    url: api.loadBoard,
  })
  if (!result) {
    return;
  }
  boardList.value = result.data
}
loadBoardList();

// 弹窗相关
const emit = defineEmits()
const submitForm = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {
      articleId: formData.value.articleId,
      boardIds: formData.value.boardIds
    };
    if (params.boardIds && params.boardIds.length == 1) {
      params.pBoardId = params.boardIds[0];
    } else if (params.boardIds && params.boardIds.length > 1) {
      params.pBoardId = params.boardIds[0]
      params.boardId = params.boardIds[1]
    }
    delete params.boardIds
    let result = await proxy.Request({
      url: api.updateBoard,
      params,
    });
    if (!result) {
      return;
    }
    dialogConfig.show = false
    emit('reload')
  });
}
const dialogConfig = reactive({
  show: false,
  title: "修改板块",
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

const updateBoard = (data) => {
  dialogConfig.show = true;
  nextTick(() => {
    formDataRef.value.resetFields();
    data.boardIds = []
    data.boardIds.push(data.pBoardId)
    if (!data.boardId == null && !data.boardId == 0) {
      data.boardIds.push(data.boardId)
    }
    formData.value = data
  })
}
defineExpose({ updateBoard })
</script>

<style lang="scss" scoped></style>
